<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;

use app\admin\model\Image;
use app\admin\model\Librarytype;
use app\admin\model\Libraryopen;
use app\admin\model\Member;
use app\admin\model\Operator;
use app\admin\service\Library as LibraryService;

use think\Db;
use think\Exception;
use think\Request;

class Library extends Base
{

    public function _initialize() {
        parent::_initialize();

        $typeId = $this->request->param('typeId');
        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere['typeId'] = $typeId;
        $defaultWhere['isDelete'] = ['neq', 1];
        $this->defaultWhere = $defaultWhere;
        $this->searchFields = [
            'name' => [
                'label'     => '名称',
                'field'     => 'name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];

        $librarytypeInfo = Librarytype::where(['id' => $typeId])->find();
        $this->assign('typeId', $typeId);
        $this->assign('typeName', $librarytypeInfo['name']);
        $this->assign('area', $this->getArea($librarytypeInfo));
        $this->assign('librarytypeInfo', $librarytypeInfo);
    }

    public function index(){
        // 分类
        $typeList = Librarytype::order('sorting ASC')->select();
        $this->assign('typeList', $typeList);

        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                //$model = $model->where($this->defaultWhere);
                $where = array_merge($this->defaultWhere, $where);
            }
            /*if($this->defaultOrder){
                $model = $model->order($this->defaultOrder);
            }*/

            $list = $model->where($where)->limit($start, $length)->order($order)->select();
            $count = $model->where($where)->count();
            foreach ($list as $item) {
                $operatorInfo = Operator::where(['id' => $item['createOper']])->field('loginName, memberId')->find();
                if ($operatorInfo) {
                    // 后台上传
                    $createOperName = $operatorInfo['loginName'];
                    if ($operatorInfo['memberId']) {
                        $createOperName = Member::where(['id' => $operatorInfo['memberId']])->value('name');
                    }
                } else {
                    // 前端上传
                    $createOperName = Member::where(['id' => $item['createOper']])->value('name');
                }

                $item['createOperName'] = $createOperName;
            }

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        return parent::index();
    }

    public function add(Request $request) {

        return parent::add($request);
    }

    public function edit(Request $request) {

        return parent::edit($request);
    }

    public function savePost(Request $request, $redirect = ''){
        $redirect = url('admin/library/index', ['typeId' => $request->param('typeId')]);
        $model = model($this->model);
        if ($request->isPost()) {
            $data = $request->param();

            if($data['fileUrl']){
                @$data['fileType'] = pathinfo($data['fileUrl'], PATHINFO_EXTENSION);
            }

            try {
                Db::startTrans();
                if(isset($data['id']) && $data['id']){
                    $data['updateDate'] = time();
                    $data['updateOper'] = $this->admin->id;
                    $data['isDelete'] = 2;

                    $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

                    if($result !== false) {
                        // 单图
                        if(isset($data['imgId']) && !empty($data['imgId'])){
                            Image::where('id', $data['imgId'])->update(['relatedId' => $data['id'], 'relatedTable' => 'Meeting']);
                        }
                        // 保存公开人员
                        $res = LibraryService::saveLibraryopen($data);
                        if($res['code'] != 1){
                            Db::rollback();
                            return $this->error($res['msg']);
                        }

                        // Query执行后的操作
                        $model->_after_update($data);

                        // 写入日志
                        $logInfo = $this->admin->name . '更新了一条' . $this->model . '数据。';
                        Common::adminLog($request, $logInfo);

                        Db::commit();
                        return $this->success('保存成功！', $redirect);
                    } else {
                        Db::rollback();
                        return $this->error($model->getError());
                    }
                }

                $data['id'] = Helper::getUUID();
                $data['createDate'] = time();
                $data['createOper'] = $this->admin->id;
                $result = $model->save($data);

                if($result !== false) {
                    // 单图
                    if(isset($data['imgId']) && !empty($data['imgId'])){
                        Image::where('id', $data['imgId'])->update(['relatedId' => $data['id'], 'relatedTable' => 'Meeting']);
                    }
                    // 保存公开人员
                    $res = LibraryService::saveLibraryopen($data);
                    if($res['code'] != 1){
                        Db::rollback();
                        return $this->error($res['msg']);
                    }

                    // Query执行后的操作
                    $model->_after_insert($data);

                    // 写入日志
                    $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('添加成功！', $redirect);
                } else {
                    Db::rollback();
                    return $this->error($model->getError());
                }
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
        } else {
            return $this->error('请求方式错误！');
        }
    }

    public function delete() {
        $model = model($this->model);
        $request = $this->request;
        $id = $request->param('id');

        $info = $model->find(['id', $id]);
        if(!$info){
            return redirect('admin/'.$this->model.'/index');
        }

        $result = $model->where('id', $id)->update(['isDelete' => 1]);

        if($result !== false){
            // Query执行后的操作
            //$model->_after_delete($id);

            $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
            Common::adminLog($request, $logInfo);

            return $this->success('删除成功！', 'admin/' . strtolower($request->controller()) . '/index');
        } else {
            return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
        }
    }

    /**
     * 移至另一分类
     */
    public function move() {
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            $ids = (Array)$param['ids'];
            foreach ($ids as $id) {
                $result = $model->where('id', $id)->update(['typeId' => $param['typeId']]);
            }

            if($result !== false) {
                return $this->success('移动成功！');
            } else {
                return $this->error('移动失败！');
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['typeId']) && $filter['typeId']){
                $where['typeId'] = $filter['typeId'];
            }
            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        return $where;
    }

    /**
     * 默认条件
     */
    public function getDefaultWhere(){
        $defaultWhere = [];
        switch ($this->admin->type) {
            case 0:
                $defaultWhere = [];
                break;
            case 1:
                $defaultWhere = ['cityId' => $this->admin->cityId];
                break;
            case 2:
                $defaultWhere = ['xianId' => $this->admin->xianId];
                break;
            case 3:
            case 6:
                $defaultWhere = ['townId' => $this->admin->townId];
                break;
            case 4:
                $defaultWhere = ['villageId' => $this->admin->villageId];
                break;

            default:
                $defaultWhere = [];
                break;
        }

        if($this->admin->memberId){
            $ids = $this->getAllowLibraryIds($this->admin->memberId); // 获取可见的文件ID集合
            $defaultWhere['id'] = ['in', $ids];
        }

        return $defaultWhere;
    }

    /**
     * 获取可见的文件ID集合
     */
    private function getAllowLibraryIds($memberId)
    {
        $libraryMdl = model($this->model);;
        $ids = [];
        // 所有人公开
        $allOpenIds = $libraryMdl->where(['openType' => 0, 'isDelete' => 2])->column('id');

        // 部分人公开
        $openIds = \app\admin\model\Libraryopen::alias('a')->where(['a.memberId' => $memberId, 'b.openType' => 1])->join('library b', 'a.libraryId = b.id')->column('a.libraryId');
        // 上传者
        $uploadIds = $libraryMdl->where(['openType' => 2, 'createOper' => $memberId, 'isDelete' => 2])->column('id');

        $ids = array_merge($allOpenIds, $openIds, $uploadIds);
        // 去重
        $ids = array_unique($ids);

        return $ids;
    }

    /**
     * 成员列表
     */
    public function memberList(){
        $request = $this->request;
        $param = $request->param();
        $model = model('Member');

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        $where = [
            'townId' => $param['townId'],
            'organizationId' => [['neq', 0], ['neq', ''], ['neq', 'null'], 'and']
        ];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            
            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        $list = $model->alias('a')->where($where)->limit($start, $length)->select();
        $count = $model->alias('a')->where($where)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 公开人员 列表
     */
    public function openmemberList(){
        $request = $this->request;
        $param = $request->param();
        $model = new Libraryopen();

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        if(empty($param['id'])){
            $result = [
                'status' => '0',
                'draw' => $param['draw'],
                'data' => [],
                'recordsFiltered' => 0,
                'recordsTotal' => 0,
            ];
            return json($result);
        }
        $where = [
            'libraryId' => $param['id']
        ];

        $join = [
            ['__MEMBER__ m', 'a.memberId = m.id'],
        ];
        $field = 'a.*, m.avatar, m.name';
        $list = $model->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->select();
        $count = $model->alias('a')->where($where)->join($join)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

}
